package com.servlet.teacher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;


/*表示客户端请求该Servlet的映射地址
* @WebServlet("/MyServlet1")
* 表示我们可以客户端通过    http://ip:端口号/上下文路径/MyServlet1 来调用此类中的doGet或doPost方法
* //如当前tomcat的访问地址为http://locahost:8080 当前的项目的下下文路径为MyWeb2
*  则该Servlet的访问地直来
*       http://locahost:8080/MyWeb2/MyServlet1
* */

@WebServlet("/MyServlet1")
public class MyServlet1 extends HttpServlet {
    public MyServlet1(){
        System.out.println("MyServlet1的构造方法被调用。");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("init被调用。");
    }

    @Override
    public void destroy() {
        System.out.println("destroy被调用。");
    }

    //http://localhost:9090/MyWeb2/MyServlet1

    private String currentLoginUserName;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //http://localhost:9090/MyWeb2/MyServlet1?userName=admin&pwd=123456

        String userName =   request.getParameter("userName");//根据请求参数的名称，获得请求参数的值，返回String类型的值

        String pwd = request.getParameter("pwd");//获得密码


        this.currentLoginUserName = userName;

        //"admin".equals(userName)        userName.equals("admin");


        System.out.println("doGet");

        PrintWriter out =  response.getWriter();

        //判断用户名为admin,且密码为123456时，返回login success字符串
        if ("admin".equals(userName) && "123456".equals(pwd)){
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            out.print(" login success " +currentLoginUserName);//往客户端输出
        }else{
            out.print(" login fail" +currentLoginUserName);
        }


         //super.doGet(req, resp);


        //得到输出流对象，调用输出流对象的write方法，就可以将响应数据发送给客户端浏览器
    // OutputStream outputStream =  response.getOutputStream();
     //  outputStream.write("hello".getBytes());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //  super.doPost(req, resp);
    }
}
